package day56;//给你一个由 '1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
//
// 岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
//
// 此外，你可以假设该网格的四条边均被水包围。
//
//
//
// 示例 1：
//
//
//输入：grid = [
//  ["1","1","1","1","0"],
//  ["1","1","0","1","0"],
//  ["1","1","0","0","0"],
//  ["0","0","0","0","0"]
//]
//输出：1
//
//
// 示例 2：
//
//
//输入：grid = [
//  ["1","1","0","0","0"],
//  ["1","1","0","0","0"],
//  ["0","0","1","0","0"],
//  ["0","0","0","1","1"]
//]
//输出：3
//
//
//
//
// 提示：
//
//
// m == grid.length
// n == grid[i].length
// 1 <= m, n <= 300
// grid[i][j] 的值为 '0' 或 '1'
//
// Related Topics 深度优先搜索 广度优先搜索 并查集 数组 矩阵
// 👍 1280 👎 0


//leetcode submit region begin(Prohibit modification and deletion)
public class L200 {

    public static void main(String[] args) {
        System.out.println(numIslands(new char[][]{{'1','0','1','1','1'},{'1','0','1','0','1'},{'1','1','1','0','1'}}));
    }

    public static int numIslands(char[][] grid) {
        //BFS,dfs，并查集
        //并查集，时间O(n^2logn)
        int count = 0;
        int[][] gridNums = new int[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++) {
            for (int i1 = 0; i1 < grid[0].length; i1++) {
                if(grid[i][i1] == '1'){
                    count++;
                    gridNums[i][i1] = count-1;
                }
            }
        }
        UnionFind unionFind = new UnionFind(count);
        for (int i = 0; i < grid.length; i++) {
            for (int i1 = 0; i1 < grid[0].length; i1++) {
                //该点-1 -1合并
                if(grid[i][i1] != '0'){
                    if(i > 0 && grid[i-1][i1] != '0'){
                        unionFind.union(gridNums[i-1][i1],gridNums[i][i1]);
                    }
                    if(i1 > 0 && grid[i][i1-1] != '0'){
                        unionFind.union(gridNums[i][i1-1],gridNums[i][i1]);
                    }
                }
            }
        }
        return unionFind.count;
    }

    public static class UnionFind{
        int[] parent;
        int count;

        public UnionFind(int n) {
            count = n;
            parent = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
            }
        }

        public int find(int x) {
            while (parent[x] != x){
                x = parent[x];
            }
            return x;
        }

        public void union(int x,int y){
            int i = find(x);
            int i1 = find(y);
            if(i == i1) return;
            parent[i] = i1;
            while (i1 != parent[y]){
                int t = parent[y];
                parent[y] = i1;
                y = t;
            }
            count--;
        }
    }
}
//leetcode submit region end(Prohibit modification and deletion)
